package com.example.administrator.szb.activity;

import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.ColorBean;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.bean.StarBean;
import com.example.administrator.szb.bean.XZJGBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/10/28.
 */

public class XZJGActivity extends BaseActivity {
    @Bind(R.id.xzjg_recyclerview)
    RecyclerView xzjgRecyclerview;
    int id_dd;
    XZJGBean xzjgBean;

    Map<Integer, String> info_id = new HashMap<Integer, String>() {
        @Override
        public String toString() {
            String info = "";
            Iterator<Integer> it = info_id.keySet().iterator();
            while (it.hasNext()) {
                info = info + info_id.get(it.next()) + ",";
            }
            return info;
        }
    };
    @Bind(R.id.xzjg_button_tj)
    Button xzjgButtonTj;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xzjg_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        initToolbar(R.id.xzjg_toolbar_include, "选择机构");
        requestData();
    }

    private void requestData() {
        id_dd = getIntent().getIntExtra("id_dd", -1);
        //initRecyclerview();
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("indent_id", id_dd + "");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_XZJG;

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, XZJGBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                xzjgBean = (XZJGBean) response;
                if (xzjgBean.getResult() == 1) {
                    initRecyclerview();
                } else {
                    Toasts.show(XZJGActivity.this, "" + xzjgBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    private void initRecyclerview() {
        /**
         * todo 将业务标签改为gridview
         */
        xzjgRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        BaseAdapter<XZJGBean.DataBean> adapter = new BaseAdapter<XZJGBean.DataBean>(this, xzjgBean.getData()) {
            @Override
            public void convert(final int position, BaseViewHolder holder, final XZJGBean.DataBean bean) {
                (holder.getView(R.id.checkBox)).setVisibility(View.VISIBLE);
                ((CheckBox) holder.getView(R.id.checkBox)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b) {
                            if (info_id.size() > 3) {
                                Toasts.show(XZJGActivity.this, "抱歉您最多只能选择3个机构...", Toast.LENGTH_SHORT);
                                return;
                            }
                            info_id.put(position, bean.getId() + "");
                        } else {
                            info_id.put(position, "");
                        }
                    }
                });
                initItem(holder, bean, position);//填充数据
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_zdyh_item;
            }
        };

        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(XZJGActivity.this, JGXQActivity.class);
                intent.putExtra("id", xzjgBean.getData().get(position).getId());
                startActivity(intent);
            }
        });
        xzjgRecyclerview.setAdapter(adapter);
    }

    private void initItem(BaseAdapter.BaseViewHolder holder, XZJGBean.DataBean dataBean, int position) {
        if (!TextUtils.isEmpty(dataBean.getHead_img())) {
            Glide.with(XZJGActivity.this).load(dataBean.getHead_img()).into((ImageView) (holder).getView(R.id.imageView20));
        }
        ((TextView) holder.getView(R.id.textView49)).setText(dataBean.getCompany() + "-" + dataBean.getName());
        if (dataBean.getCompany() == null) {
            ((TextView) holder.getView(R.id.textView50)).setVisibility(View.INVISIBLE);
        } else {
            ((TextView) holder.getView(R.id.textView50)).setVisibility(View.INVISIBLE);
            //((TextView)holder.getView(R.id.textView50)).setText(dataBean.getCompany());
        }
        if (dataBean.getCity() == null) {
            ((TextView) holder.getView(R.id.textView51)).setVisibility(View.INVISIBLE);
        } else {
            ((TextView) holder.getView(R.id.textView51)).setText((String) dataBean.getCity());
        }


        /**
         * 显示业务标签
         */

        showYW(dataBean, holder, position);

        /**
         * 显示星星
         */
        showStar(dataBean, holder);
    }

    private void showStar(final XZJGBean.DataBean dataBean, BaseAdapter.BaseViewHolder holder) {
        final ArrayList<StarBean> mdata = new ArrayList<>();
        RecyclerView recyclerView = ((RecyclerView) holder.getView(R.id.zdyh_recyclerview_star));
        recyclerView.setLayoutManager(new GridLayoutManager(XZJGActivity.this, 5));
        for (int i = 0; i < dataBean.getEvaluate() / 2 + dataBean.getEvaluate() % 2; i++) {
            StarBean b = new StarBean();
            mdata.add(b);
        }
        BaseAdapter<StarBean> adapter = new BaseAdapter<StarBean>(XZJGActivity.this, mdata) {
            @Override
            public void convert(int position, BaseViewHolder holder, StarBean starBean) {
                ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.start);
                if (position == mdata.size() - 1 && dataBean.getEvaluate() % 2 != 0) {
                    ((ImageView) holder.getView(R.id.view_zdyh_star)).setImageResource(R.drawable.star_half);
                }
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_zdyh_star;
            }
        };
        recyclerView.setAdapter(adapter);
    }

    private void showYW(XZJGBean.DataBean dataBean, BaseAdapter.BaseViewHolder holder, final int position) {

        RecyclerView recyclerView = ((RecyclerView) holder.getView(R.id.zdyh_recyclerview_ywbq));
        /**
         * 截获事件，业务标签的recyclerview 会劫持事件，如果不加上点击失效
         */
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {//此处是点击按下时才执行跳转动作
                    // Toasts.show(mActivity, "....", Toast.LENGTH_SHORT);
                    Intent intent = new Intent(XZJGActivity.this, JGXQActivity.class);
                    intent.putExtra("id", xzjgBean.getData().get(position).getId());
                    startActivity(intent);
                    //startActivity(new Intent(ProfileEdit.this, EditDepartment.class));
                }
                return false;
            }
        });


        recyclerView.setFocusableInTouchMode(false);

        recyclerView.setLayoutManager(new GridLayoutManager(XZJGActivity.this, 4));
        BaseAdapter<XZJGBean.DataBean.BusinessBean> adapter = new BaseAdapter<XZJGBean.DataBean.BusinessBean>(XZJGActivity.this, dataBean.getBusiness(), 4) {
            @Override
            public void convert(int position, BaseViewHolder holder, XZJGBean.DataBean.BusinessBean businessBean) {
                GradientDrawable drawable;
                ((TextView) holder.getView(R.id.view_jgxq_text)).setText(businessBean.getTitle());
                try {
                    Class<?> c = null;
                    c = Class.forName("bean.ColorBean$DataBean");
                    ColorBean.DataBean obj = (ColorBean.DataBean) c.newInstance();
                    //第一个参数写的是方法名,第二个\第三个\...写的是方法参数列表中参数的类型
                    Method method = c.getMethod("get_$" + businessBean.getId());
                    //String str2 = (String) method.invoke(WecomeActivity.colorBean.getData());


                    drawable = (GradientDrawable) ((TextView) holder.getView(R.id.view_jgxq_text)).getBackground();
                    //drawable.setColor(Color.parseColor(str2));
                } catch (Exception e) {

                }


            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_jgxq_item;
            }
        };

        recyclerView.setAdapter(adapter);


    }

    @OnClick(R.id.xzjg_button_tj)
    public void onViewClicked() {
        if (info_id.size() <= 0){
            Toasts.show(this, "请选择机构哦。。。", Toast.LENGTH_SHORT);
            return;
        }

        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("users_id",info_id+"");
        map.put("indent_id",id_dd+"");
        String url = URLAddress.URLBASE + URLAddress.URL_TJJG;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean bean = (ResultBean) response;
                if (bean.getResult() == 1){
                    Toasts.show(XZJGActivity.this, "提交成功", Toast.LENGTH_SHORT);
                    ProductDetailActivity.canRefresh = true;
                    finish();
                }else{
                    Toasts.show(XZJGActivity.this, ""+bean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }
}
